import React from 'react';
import { navigate } from 'utils/router';
import utils from 'utils';
import { getFeature } from 'utils/features';
import MemberList from 'components/memberList';
import { PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import TextAvatar from '@txdfe/at-text-avatar';
import { YunxiaoIcon } from '@alife/devops-ui';
import track from 'utils/track';
import intl from '../../../../../locale';
export default class ProjectNav extends React.Component {
  constructor(props) {
    super(props);
    // ?open_member_diaolog=true自动弹出成员面板
    const open_member_diaolog = utils.getUrlSearchParam('open_member_diaolog') || '';
    const states = ProjectNav.getDerivedStateFromProps(props);
    this.state = {
      showMemberList: open_member_diaolog === 'true',
      ...states,
    };
  }

  static getDerivedStateFromProps(props) {
    const { projectInfo, isProjectInfoFetched } = (props.project && props.project.root) || {};
    if (!isProjectInfoFetched) {
      return {};
    }
    const pageInfo = (props.root && props.root.pageInfo) || {};
    if (!pageInfo.pathResource) {
      return;
    }
    // 若库为空，则隐藏以下tab 或者导入状态为failed(初始化空库状态failed不变，结合isExist进行判断)/started
    const isImportUnfinished =
      projectInfo.import_status === 'started' ||
      projectInfo.import_status === 'stopping' ||
      (projectInfo.import_status === 'failed' && pageInfo.pathResource.isExist === 'false');
    // const hiddenKeys = isImportUnfinished || pageInfo.pathResource.isEmpty === 'true' ? ['merge', 'commits', 'mergerequest', 'branches', 'tags', 'security'] : [];
    let hiddenKeys = [];
    if (isImportUnfinished) {
      hiddenKeys = [
        'merge',
        'commits',
        'mergerequest',
        'branches',
        'tags',
        'security',
        'pipeline',
        'insight',
      ];
    } else if (pageInfo.pathResource.isEmpty === 'true') {
      hiddenKeys = ['merge', 'commits', 'branches', 'tags'];
    }
    let hideMember = false;
    const extendable = !isImportUnfinished;
    if (projectInfo.import_status === 'started' || projectInfo.import_status === 'stopping') {
      hideMember = true;
    }
    // 在库内，状态是none、finished、failed，并且isExist==true时，并且有权限时，展示设置入口
    const hideSetting = !(
      ['none', 'finished', 'failed'].includes(projectInfo.import_status) &&
      pageInfo.pathResource.isExist === 'true'
    );
    return {
      hiddenKeys,
      hideMember,
      hideSetting,
      extendable,
    };
  }

  componentDidMount() {
    if (this.props.root.pageInfo.assetsName === 'projectMergeRequestDetail') {
      localStorage.isSidebarStick = 'false';
      this.props.onSidebarChange(false, true);
      window.TB_NAVIGATION.foldSidebar();
    }
    const active = this.getActiveKeyFromAssetsName();
    this.initSidebar(active, true);
  }

  componentDidUpdate(prevProps, prevState) {
    const { assetsName } = this.props.root.pageInfo;
    const preAssetsName = prevProps.root.pageInfo.assetsName;
    const { isCodeupGuideFlowActive, isCodeupGuideMergeActive, isCodeupGuideSafetyActive } =
      this.props.project.root;
    if (
      prevProps.project.root.isCodeupGuideFlowActive !== isCodeupGuideFlowActive ||
      prevProps.project.root.isCodeupGuideMergeActive !== isCodeupGuideMergeActive ||
      prevProps.project.root.isCodeupGuideSafetyActive !== isCodeupGuideSafetyActive
    ) {
      const active = this.getActiveKeyFromAssetsName();
      this.initSidebar(active);
      return true;
    }
    if (assetsName !== preAssetsName && assetsName === 'projectMergeRequestDetail') {
      this.props.onSidebarChange(false, true);
      localStorage.isSidebarStick2 = localStorage.isSidebarStick;
      localStorage.isSidebarStick = 'false';
      window.TB_NAVIGATION.foldSidebar();
    }
    if (assetsName !== preAssetsName && preAssetsName === 'projectMergeRequestDetail') {
      if (localStorage.isSidebarStick !== localStorage.isSidebarStick2) {
        localStorage.isSidebarStick = localStorage.isSidebarStick2;
        const isStick = localStorage.isSidebarStick2 === 'true';
        this.props.onSidebarChange(isStick, true);
        if (isStick) {
          window.TB_NAVIGATION.stickSidebar();
        } else {
          window.TB_NAVIGATION.foldSidebar();
        }
      }
    }
    if (
      prevState.hiddenKeys !== this.state.hiddenKeys ||
      prevState.hideMember !== this.state.hideMember ||
      prevState.hideSetting !== this.state.hideSetting
    ) {
      const active = this.getActiveKeyFromAssetsName();
      this.initSidebar(active);
    }
    if (prevProps.showWiki !== this.props.showWiki) {
      const active = this.getActiveKeyFromAssetsName();
      this.initSidebar(active);
    }
  }

  componentWillUnmount() {
    localStorage.isSidebarStick = localStorage.isSidebarStick2;
    //   window.TB_NAVIGATION.removeSidebar();
  }

  getCurrentBreathe = () => {
    const { isCodeupGuideFlowActive, isCodeupGuideMergeActive, isCodeupGuideSafetyActive } =
      this.props.project.root;
    const { pathResource } = window.FORCE;
    if (isCodeupGuideFlowActive) return `/${pathResource.fullPath}/pipeline`;
    if (isCodeupGuideMergeActive) return `/${pathResource.fullPath}/merge_requests`;
    if (isCodeupGuideSafetyActive) return `/${pathResource.fullPath}/project_security`;
    return undefined;
  };

  initSidebar = (active, didMount) => {
    const { projectInfo } = (this.props.project && this.props.project.root) || {};
    const main = this.getMain();
    const extra = this.getExtra();
    const breathe = this.getCurrentBreathe();

    if (projectInfo.name) {
      window.TB_NAVIGATION.initOrUpdateSidebar({
        header: {
          logoUseJsx: !projectInfo.avatar_url,
          logo:
            projectInfo.avatar_url || (
              <TextAvatar
                text={projectInfo.name.toUpperCase()}
                image={projectInfo.avatar_url}
                isCover
              />
            ) ||
            'https://img.alicdn.com/imgextra/i4/O1CN01W1NAtC1tzDzobMP9r_!!6000000005972-2-tps-122-122.png',
          name: projectInfo.name,
        },
        active,
        main,
        extra,
        level: 2,
        breathe,
      });
    } else {
      // projectInfo没拿回来前，先展示空侧导
      window.TB_NAVIGATION.initOrUpdateSidebar({
        active,
        main: [],
        extra: null,
        level: 2,
        breathe,
      });
    }

    if (breathe && didMount === breathe) {
      // 点击breathe菜单
      const { pathResource } = window.FORCE;
      let action = '';
      if (breathe === `/${pathResource.fullPath}/pipeline`) {
        action = 'flow';
      } else if (breathe === `/${pathResource.fullPath}/merge_requests`) {
        action = 'mr';
      } else if (breathe === `/${pathResource.fullPath}/project_security`) {
        action = 'scan';
      }
      action &&
        track({
          action,
          page: 'repo-guidance',
        });
    } else if (didMount && typeof didMount === 'boolean') {
      window.TB_NAVIGATION.ready(() => {
        window.TB_NAVIGATION.onSidebarChange(({ isStick }) => {
          this.props.onSidebarChange(isStick);
        });
      });
    }
  };

  getMain = () => {
    const { showWiki } = this.props;
    const { hiddenKeys } = this.state;
    const { pathResource } = window.FORCE;
    let { repoSize, branchCount, mergeRequestCount, tagCount } = pathResource;
    try {
      const propsPathResource = this.props.root.pageInfo.pathResource;
      repoSize = propsPathResource.repoSize;
      branchCount = propsPathResource.branchCount;
      // commitCount = propsPathResource.commitCount;
      mergeRequestCount = propsPathResource.mergeRequestCount;
      tagCount = propsPathResource.tagCount;
      // eslint-disable-next-line no-empty
    } catch (error) {}

    // repoSize以M为单位，前端处理不到1M用K， 不到1G用M, >1G 就保留两位小数
    let beautifulRepoSize;
    const repoSizeNum = Number(repoSize);
    if (!repoSize || !repoSizeNum) {
      beautifulRepoSize = '';
    } else if (repoSizeNum < 1) {
      beautifulRepoSize = `(${Math.ceil(repoSizeNum * 1024 * 100) / 100}K)`;
    } else if (repoSizeNum > 1024) {
      beautifulRepoSize = `(${Math.ceil((repoSizeNum / 1024) * 100) / 100}G)`;
    } else {
      beautifulRepoSize = `(${Math.ceil(repoSizeNum * 100) / 100}M)`;
    }
    // 导入中不显示大小
    const { projectInfo } = (this.props.project && this.props.project.root) || {};
    if (!['none', 'finished', 'failed'].includes(projectInfo.import_status)) {
      beautifulRepoSize = '';
    }

    const dataSource = [
      {
        key: 'files',
        id: `/${pathResource.fullPath}`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="code-basement-line" />,
        },
        name: intl.get(
          {
            id: 'code-assets.containers.projectTab.SourceFileBeautifulreposize',
            defaultMessage: '源文件{beautifulRepoSize}',
          },
          { beautifulRepoSize },
        ),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.source_file'),
      },
      {
        key: 'commits',
        id: `/${pathResource.fullPath}/commits/${utils.revisionEncodeURI(pathResource.defaultBranch)}`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="commit-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.projectTab.Submitted',
          defaultMessage: '提交',
        }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.submit'),
      },
      {
        key: 'branches',
        id: `/${pathResource.fullPath}/branches`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="branches-line" />,
        },
        name: (
          <div className="nav-item">
            {intl.get({ id: 'code-assets.containers.projectTab.Branch', defaultMessage: '分支' })}
            {Number(branchCount) ? <span className="nav-item-badge">{branchCount}</span> : null}
          </div>
        ),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.branch'),
      },
      {
        key: 'tags',
        id: `/${pathResource.fullPath}/tags`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="tag-line" />,
        },
        name: (
          <div className="nav-item">
            {intl.get({ id: 'code-assets.containers.projectTab.Label', defaultMessage: '标签' })}
            {Number(tagCount) ? <span className="nav-item-badge">{tagCount}</span> : null}
          </div>
        ),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.tag'),
      },
      {
        key: 'mergerequest',
        id: `/${pathResource.fullPath}/merge_requests`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="pull-request-line" />,
        },
        name: (
          <div className="nav-item">
            {intl.get({
              id: 'code-assets.containers.projectTab.MergeRequest',
              defaultMessage: '合并请求',
            })}
            {Number(mergeRequestCount) ? (
              <span className="nav-item-badge">{mergeRequestCount}</span>
            ) : null}
          </div>
        ),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.mr'),
      },
      {
        key: 'pipeline',
        id: `/${pathResource.fullPath}/pipeline`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="pipelines-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.projectTab.AssemblyLine',
          defaultMessage: '流水线',
        }),
        onClick: this.handleClick,
        isShow: getFeature('module_enable.repository.flow'),
      },
      //   {
      //     key: 'pipeline',
      //     title: (
      //       <div className="project-tab-insight">
      //         <span style={{ padding: '0 4px' }}>
      //           {intl.get({
      //             id: 'code-assets.containers.projectTab.AssemblyLine',
      //             defaultMessage: '流水线',
      //           })}
      //         </span>
      //         {hasInsightDot && <Badge dot />}
      //       </div>
      //     ),

      //     href: `/${pathResource.fullPath}/pipeline`,
      //     onClick: () => {
      //       this.setState({
      //         hasInsightDot: false,
      //       });

      //       setCachedRepoId(insightKey);
      //     },
      //   },
      {
        key: 'security',
        id: `/${pathResource.fullPath}/project_security`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="detection-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.projectTab.Safety', defaultMessage: '安全' }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.security'),
      },
      {
        key: 'insight',
        id: `/${pathResource.fullPath}/insight`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="bar-chart-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.projectTab.Report', defaultMessage: '报表' }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.insight'),
      },
      {
        key: 'activity',
        id: `/${pathResource.fullPath}/activity`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="historyrecord-line" />,
        },
        name: intl.get({
          id: 'code-assets.containers.projectTab.SummaryInvestingComZa',
          defaultMessage: '动态',
        }),
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.activity'),
      },
    ];

    if (getFeature('project.wiki.provider') === 'thoughts') {
      if (showWiki) {
        dataSource.push({
          key: 'wiki',
          id: `/${pathResource.fullPath}/wiki`,
          icon: {
            useJsx: true,
            jsx: <YunxiaoIcon type="guidebook-2-line" />,
          },
          name: '文档',
          onClick: this.handleClick,
          isShow: getFeature('page_enable.project.wiki'),
        });
      }
    } else if (getFeature('project.wiki.provider') === 'csdn') {
      dataSource.push({
        key: 'wiki',
        id: `/${pathResource.fullPath}/wiki`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="guidebook-2-line" />,
        },
        name: 'Wiki',
        onClick: this.handleClick,
        isShow: getFeature('page_enable.project.wiki'),
      });
    }

    // if (getFeature('page_enable.project.issue')) {
    //   dataSource.push({
    //     key: 'issue',
    //     id: `/${pathResource.fullPath}/issue`,
    //     icon: {
    //       type: 'italic',
    //     },
    //     name: 'Issue',
    //     onClick: this.handleClick,
    //   });
    // }

    const shownDataSource = dataSource.filter((item) => {
      return hiddenKeys && item.isShow && !hiddenKeys.includes(item.key);
    });
    return shownDataSource;
  };

  getExtra = () => {
    const { pathResource } = window.FORCE;
    const { role } = pathResource;
    const { hideMember, hideSetting } = this.state;

    const shownDataSource = [];

    if (!hideMember) {
      shownDataSource.push({
        id: 'projectMembers',
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="member-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.projectTab.Members', defaultMessage: '成员' }),
        onClick: this.handleClickOpenMemberList,
      });
    }
    if (!hideSetting && PROJECT_ADMIN_ROLES.includes(role)) {
      shownDataSource.push({
        id: `/${pathResource.fullPath}/settings`,
        icon: {
          useJsx: true,
          jsx: <YunxiaoIcon type="setting-line" />,
        },
        name: intl.get({ id: 'code-assets.containers.projectTab.Set', defaultMessage: '设置' }),
        onClick: this.handleClick,
      });
    }

    return shownDataSource;
  };

  handleClickOpenMemberList = () => {
    this.setState({
      showMemberList: true,
    });
  };

  handleClick = (v) => {
    this.initSidebar(v.id, v.id);
    navigate(v.id, { state: { forceUpdate: true } });
  };

  // 由资源名判断高亮哪个tab
  getActiveKeyFromAssetsName = () => {
    const { assetsName, pathResource } = window.FORCE;
    const dataSource = this.getMain();
    const key = assetsName.replace('project', '').toLocaleLowerCase();
    let result;
    if (dataSource.some((item) => item.key === key)) {
      result = key;
    } else {
      switch (key) {
        case 'blame':
          result = 'file';
          break;
        case 'commitdetail':
        case 'compare':
          result = 'commits';
          break;
        case 'mergerequestdetail':
          result = 'mergerequest';
          break;
        case 'settings':
          result = 'settings';
          break;
        case 'security':
          result = 'security';
          break;
        default:
          break;
      }
    }

    if (result === 'settings') {
      return `/${pathResource.fullPath}/settings`;
    }

    const activeId = dataSource.find((item) => item.key === result)?.id;
    return activeId;
  };

  renderMemberDialog = () => {
    const { pathResource } = window.FORCE;
    const { hideMember, showMemberList } = this.state;
    if (hideMember) {
      return null;
    }
    return (
      <MemberList
        pathResourceId={pathResource.id}
        pathResourceType="project"
        align="tr br"
        role={pathResource.role}
        visible={showMemberList}
        onClose={() => {
          this.setState({
            showMemberList: false,
          });

          utils.getUrlSearchParam('open_member_diaolog') &&
            window.history.replaceState({}, null, window.location.pathname);
        }}
      />
    );
  };

  render() {
    return <>{this.renderMemberDialog()}</>;
  }
}
